/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trocabi.Socle;

/**
 *
 * @author philippe
 */
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;

public class JPriceTextField extends JFormattedTextField {
    public JPriceTextField() {
        super(); 
        NumberFormatter defaultFormatter = new NumberFormatter(new DecimalFormat("#,###0.00 €"));
        NumberFormatter displayFormatter = new NumberFormatter(new DecimalFormat("#,###0.00 €"));
        NumberFormatter editFormatter = new NumberFormatter(new DecimalFormat("#,###0.00"));
        // set their value classes
        defaultFormatter.setValueClass(Double.class);
        displayFormatter.setValueClass(Double.class);
        editFormatter.setValueClass(Double.class);  
        // create and set the DefaultFormatterFactory
        DefaultFormatterFactory priceFactory = new DefaultFormatterFactory(defaultFormatter,displayFormatter,editFormatter);
        this.setFormatterFactory(priceFactory); 
    }
   
    public double getPrice() { 
        return (getValue()==null?0.0:(Double) getValue());
    }
    
    public void setPrice(double price) {
        this.setValue((Double) price);
    }
    
    static public String formatPrice(double price) {
        return String.format("%3.2f €",price);
    }
    /**
     * Sample usage
     * @param args
     * @throws ParseException 
     */
    public static void main(final String args[]) throws ParseException {
        JFrame frame = new JFrame("Formatted Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        final JPriceTextField pricing=new JPriceTextField();
        pricing.setPrice(10.15);
        JButton btOK=new JButton("Ok");
        btOK.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                   System.out.println(String.format("%f",pricing.getPrice()));
            }
        });
        frame.add(pricing, BorderLayout.NORTH);
        frame.add(btOK, BorderLayout.SOUTH);
        frame.setSize(250, 100);
        frame.setVisible(true);
    }
}